import Styled from 'styled-components';
import React, { Component } from 'react';
import { Form, Row, Col, Input, Button, Select, Checkbox, Radio, DatePicker } from 'antd';
import PopupSelect from '@/components/ui/PopupSelect';
import http from '@/utils/http';

const Box = Styled.div`
  padding: 0 20px;
  border-bottom: 1px solid #CCCCCC;
  .form-btn {
    line-height: 40px;
    ${props => props.btnCenter ? 'text-align: center;margin-bottom: 12px;' : ''}
  }
`;
class SearchForm extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.dataKey = 'code';
    this.dataValue = 'name';
  }

  componentDidMount() {
    let { items } = this.props;
    items.forEach(i => {
      if (i.url) {
        http.get(i.url).then(response => {
          let dataset = response.data;
          i.handleDataset && (dataset = i.handleDataset(dataset));
          this.setState({
            [`${i.key}`]: dataset
          });
        });
      } else if (i.dataset) {
        this.setState({
          [`${i.key}`]: i.dataset
        });
      }
    });
  }

  getFormItem(item) {
    switch (item.type) {
      case 'checkbox':
        if (item.url || item.dataset) {
          return this.getComponent(Checkbox.Group, Checkbox, {}, item);
        } else {
          return <Checkbox value={item.key} />;
        }
      case 'radio':
        return this.getComponent(Radio.Group, Radio, {}, item);
      case 'dropdown':
        return this.getComponent(Select, Select.Option, {
          mode: item.multi ? 'multiple' : '',
          placeholder: item.placeholder,
        }, item);
      case 'datepicker':
        return <DatePicker placeholder={item.placeholder} {...item.customParameters} allowClear={false} />
      case 'popupselect':
        return <PopupSelect {...item.config} />
      default:
        return <Input placeholder={item.placeholder} />;
    }
  }

  getComponent(Parent, Child, params, item) {
    const dataKey = item.dataKey || this.dataKey;
    const dataValue = item.dataValue || this.dataValue;
    return (
      <Parent {...params} >
        {this.state[item.key]?.map(i => (
          <Child key={i[dataKey]} value={i[dataKey]}>{i[dataValue]}</Child>
        ))}
      </Parent>
    );
  }

  handleSubmit(e) {
    e.preventDefault();
    const values = this.props.form.getFieldsValue();
    let json = {};
    for (const i in values) {
      let temp = values[i];
      if (temp) {
        if (typeof temp === 'string') {
          temp = temp.trim();
        } else if (temp._isAMomentObject) {
          temp = temp.format('YYYYMMDD');
        }
        temp !== undefined && (json[i] = temp);
      }
    }
    // eslint-disable-next-line
    this.props.fnSearch?.(json);
  }

  handleClickReset() {
    this.props.form.resetFields();
    // eslint-disable-next-line
    // this.props.fnSearch?.(); // 是否需要重置表格数据，待定
  }

  render() {
    const { items } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    return (
      <Box btnCenter={items.length > 2}>
        <Form {...formItemLayout} onSubmit={this.handleSubmit.bind(this)}>
          <Row gutter={24}>
            {items.map(i => (
              <Col span={8} key={i.key}>
                <Form.Item label={i.label}>
                  {getFieldDecorator(i.key, {
                    initialValue: i.initialValue
                  })(this.getFormItem(i))}
                </Form.Item>
              </Col>
            ))}
            <Col span={items.length > 2 ? 24 : 8} className="form-btn">
              <Button type="primary" htmlType="submit" icon="search">搜索</Button>
              <Button style={{ marginLeft: 12 }} icon="sync" onClick={this.handleClickReset.bind(this)}>重置</Button>
            </Col>
          </Row>
        </Form>
      </Box>
    );
  }
}

export default Form.create({name: `form_${Math.random().toString().substr(2, 4)}`})(SearchForm);
